//silkcms.js

function createJsNode(pSrc){
    var jsNode = document.createElement('script');
	jsNode.type = 'text/javascript';
	jsNode.src = pSrc;
    return jsNode;
}

function createCssNode(pHref){
    var cssNode = document.createElement('link');
	cssNode.rel = 'stylesheet';
	cssNode.type = 'text/css';
	cssNode.href = pHref;
    return cssNode;
}

//bootstrap js dependencies

var headNode = document.getElementsByTagName("head")[0];
var firstHeadNode = headNode.firstChild;

//var cssNode = createCssNode('/assets/styles/css.php?include=jquery-ui-theme,admin');
//headNode.insertBefore(cssNode, firstHeadNode);

var jsNode = createJsNode('/assets/scripts/js.php?include=jquery.min,jquery.entwine,jquery-ui.min,codemirror/js/codemirror');
//headNode.insertBefore(jsNode, cssNode.nextSibling);
headNode.insertBefore(jsNode, firstHeadNode.nextSibling);

//wait until we have everyone's undivided attention
jsNode.onload = silkReady;

function silkReady(){
    if (typeof console != 'undefined') console.log('Silk Ready!');

    jQuery(document).ready(function(){
	if (typeof console != 'undefined') console.log('Document Ready!');

	//Init jquery-ui tabs
	jQuery('.silk-cms-tabs').tabs();

	jQuery('table.silk-cms-list').each(function(){
	    jQuery(this).find('th').addClass('ui-state-default');
	    jQuery(this).find('td').addClass('ui-widget-content');
	    jQuery(this).find('tr').hover(
		function(){
		    jQuery(this).children('td').addClass('ui-state-hover');
		},
		function(){
		    jQuery(this).children('td').removeClass('ui-state-hover');
		}
	    )
	});
    });

    jQuery('a.lightbox').entwine({
	'onclick': function(){
	    alert('!');
	    jQuery('body').append('div id="silk-cms-lightbox___"></div>');
	    var lb = jQuery('div#silk-cms-lightbox___');
	    var url = jQuery(this).attr('href');

	    lb.html('<iframe src="' + url + '"></iframe>')
	    lb.dialog({
		title: jQuery(this).attr('title')
	    });
	    lb.dialog('open');
	    return false;
	}
    });

    // control jquery ui hover states on sidepanel links
    jQuery('.silk-side-panel .silk-panel-content li').entwine({
	'onmouseover': function(){
	    jQuery(this).addClass('ui-state-hover');
	},
	'onmouseout': function(){
	    jQuery(this).removeClass('ui-state-hover');
	}
    });

    // Start type template/action manager js
    jQuery('tr#default-template-row').entwine({
	'instantiateTemplate': function(pName, pContent){
	    var newRow = jQuery(this).clone();

	    newRow.find('span.template_name').html(pName);
	    newRow.find('input.hidden_template_name').val(pName);
	    newRow.find('input.hidden_template_content').val(pContent);

	    jQuery('table#type-templates tbody').append(newRow);
	}
    });

    jQuery('div#silk-cms-template-editor').entwine({
	'openEditor': function(pTableRow){
	    jQuery(this).prepopulateFields(pTableRow);

	    jQuery('button#update-template').entwine({

		'onclick': function(event){
		    jQuery('div#silk-cms-template-editor').commitEditor(pTableRow);
		    return false;
		}
	    });

	    jQuery('button#cancel-template').entwine({

		'onclick': function(event){
		    jQuery('div#silk-cms-template-editor').cancelEditor();
		    return false;
		}
	    });

	    jQuery('div#silk-cms-type-template-list').hide('fast', function() { jQuery('div#silk-cms-template-editor').show('fast'); });
	},
	'cancelEditor': function(){
	    jQuery(this).hide('fast', function(){ jQuery('div#silk-cms-type-template-list').show('fast'); });
	    jQuery('input#template-name').val('');
	    jQuery('textarea#template-content').html('');
	},
	'commitEditor': function(pTableRow){
	    if (pTableRow){
		pTableRow.find('input.hidden_template_name').val(jQuery('input#template-name').val());
		pTableRow.find('input.hidden_template_content').val(jQuery('textarea#template-content').val());
	    } else {
		jQuery('tr#default-template-row').instantiateTemplate(jQuery('input#template-name').val(), jQuery('textarea#template-content').val());
	    }
	    jQuery(this).hide('fast', function(){ jQuery('div#silk-cms-type-template-list').show('fast'); });
	},
	'prepopulateFields': function(pTableRow){
	    if (pTableRow){
		jQuery('input#template-name').val(pTableRow.find('input.hidden_template_name').val());
		jQuery('textarea#template-content').val(pTableRow.find('input.hidden_template_content').val());
	    } else {
		jQuery('input#template-name').val('');
		jQuery('textarea#template-content').val('');
	    }
	}
    });

    //Open Type Template Editor form and edit existing attribute
    jQuery('a.template-edit-link').entwine({
	'onclick': function(){
	    jQuery('div#silk-cms-template-editor').openEditor(jQuery(this).parent().parent());
	}
    });

    //Open Type Template Editor form and create new attribute
    jQuery('a.template-add-link').entwine({
	'onclick': function(){
	    jQuery('div#silk-cms-template-editor').openEditor();
	}
    });

    //Remove existing attribute row
    jQuery('a.template-delete-link').entwine({
	'onclick': function(){
	    jQuery(this).parent().parent().remove();
	}
    });

    //Start type meta management js
    jQuery('tr#default-type-meta-row').entwine({

	'instantiateAttribute': function(pName, pInputType, pDefaultValue, pListValues, pValidator){
	    var newRow = jQuery(this).clone();

	    newRow.find('td.name_col span').html(pName);
	    newRow.find('td.input_type_col span').html(pInputType);

	    newRow.find('input.hidden_meta_name').val(pName);
	    newRow.find('input.hidden_meta_input_type').val(pInputType);
	    if (pDefaultValue)
		newRow.find('input.hidden_meta_default_value').val(pDefaultValue);
	    if (pListValues)
		newRow.find('input.hidden_meta_list_values').val(pListValues);
	    if (pValidator)
		newRow.find('input.hidden_meta_validator').val(pValidator);

	    jQuery('table#type-meta-attributes tbody').append(newRow);
	}
    });

    jQuery('div#silk-cms-type-meta-editor').entwine({

	'showManualListValueEditor': function(pTableRow, pCurrentVals){

	    jQuery('select#type-meta-manual-list-values').entwine({

		'addValue': function(pVal){

		    if (pVal){
			jQuery(this).append('<option>' + pVal + '</option>');
			jQuery('input#type-meta-manual-list-string').val('');
		    }
		},

		'updateValue': function(pVal){

		    if (pVal){
			jQuery('select#type-meta-manual-list-values option:selected').replaceWith('<option>' + pVal + '</option>');
			jQuery('input#type-meta-manual-list-string').val('');
		    }
		},

		'deleteValue': function(pVal){

		    if (pVal){
			jQuery('select#type-meta-manual-list-values option:selected').remove();
			jQuery('input#type-meta-manual-list-string').val('');
		    }
		},

		'onchange': function(){
		    jQuery('input#type-meta-manual-list-string').val(jQuery(this).val());
		    jQuery('button#type-meta-manual-list-edit').removeAttr('disabled');
		    jQuery('button#type-meta-manual-list-delete').removeAttr('disabled');
		}

	    });

	    jQuery('button#type-meta-manual-list-add').entwine({

		'onclick': function(){
		    var strval = jQuery('input#type-meta-manual-list-string').val();
		    jQuery('select#type-meta-manual-list-values').addValue(strval);
		    return false;
		}
	    });

	    jQuery('button#type-meta-manual-list-edit').entwine({

		'onclick': function(){
		    var strval = jQuery('input#type-meta-manual-list-string').val();
		    jQuery('select#type-meta-manual-list-values').updateValue(strval);
		    return false;
		}
	    });

	    jQuery('button#type-meta-manual-list-delete').entwine({

		'onclick': function(){
		    var strval = jQuery('input#type-meta-manual-list-string').val();
		    jQuery('select#type-meta-manual-list-values').deleteValue(strval);
		    return false;
		}
	    });


	    if (pCurrentVals){
		eval('var list_values = ' + pCurrentVals);
		jQuery.each(list_values, function(i, current_val){ jQuery('select#type-meta-manual-list-values').addValue(current_val); });
// 		jQuery('input#type-meta-list-value-source-manual').click();
	    }

	    jQuery('div#object-list-values').hide('fast', function(){ jQuery('div#manual-list-values').show('fast'); });

	},

	'showObjectListValueEditor': function(pTableRow, pCurrentVals){
	    if (pCurrentVals){
		jQuery('select#type-meta-object-types').val(pCurrentVals.replace(/@Type=/, ''));
	    }

	    jQuery('div#manual-list-values').hide('fast', function(){ jQuery('div#object-list-values').show('fast'); });
	},

	'showListValueEditor': function(pTableRow){

	    jQuery('div#type-meta-list-value-sources').find('input[type=radio]').removeAttr('checked');
	    jQuery('div.list-value-block').hide();
	    jQuery('div#type-meta-list-value-sources').show('fast');

	    if (pTableRow)
		var current_vals = pTableRow.find('input.hidden_meta_list_values').val();
	    else
		var current_vals = null;

	    jQuery('input#type-meta-list-value-source-manual').entwine({
		'onclick': function(){
		    jQuery('div#silk-cms-type-meta-editor').showManualListValueEditor(pTableRow, current_vals);
		}
	    });

	    jQuery('input#type-meta-list-value-source-objects').entwine({
		'onclick': function(){
		    jQuery('div#silk-cms-type-meta-editor').showObjectListValueEditor(pTableRow, current_vals);

		}
	    });

	    if (current_vals){
		if (current_vals.match(/@Type=.*/)){
		    jQuery('input#type-meta-list-value-source-objects').click();
		} else if (current_vals){
		    jQuery('input#type-meta-list-value-source-manual').click();
		}
	    }

	},

	'hideListValueEditor': function(){
	    jQuery('type-meta-list-value-sources').hide('fast');
	},

	'prepopulateEditor': function(pTableRow){
	    if (pTableRow){
		jQuery('input#type-meta-name').val(pTableRow.find('input.hidden_meta_name').val());
		jQuery('select#type-meta-input-type').val(pTableRow.find('input.hidden_meta_input_type').val());
	    }
	},

	'cancelEditor': function(){
	    jQuery('div#silk-cms-type-meta-editor').hide('fast', function(){  jQuery('div#silk-cms-type-meta-list').show('fast'); });
	},

	'commitEditor': function(pTableRow){
	    var meta_name = jQuery('input#type-meta-name').val();
	    var meta_input_type = jQuery('select#type-meta-input-type').val();
	    var meta_default_value = jQuery('input#type-meta-default-value').val();

	    if (meta_input_type == 'Select'){

		var list_type = jQuery('input[name=type-meta-list-value-source-type]:checked').val();
		if (list_type == 'manual'){
		    var manual_vals = jQuery('select#type-meta-manual-list-values').val();
		    if (manual_vals.length > 0)
			var meta_list_values = "[" + manual_vals.join(',') + "]";
		    else
			var meta_list_values = "";
		} else if (list_type == 'object'){
		    var type_val = jQuery('select#type-meta-object-types').val();
		    var meta_list_values = '@Type=' + type_val;
		}
	    }

	    if (pTableRow){
		pTableRow.find('input.hidden_meta_name').val(meta_name);
		pTableRow.find('span.meta_name').html(meta_name);
		pTableRow.find('input.hidden_meta_input_type').val(meta_input_type);
		pTableRow.find('span.meta_input_type').html(meta_input_type);
		pTableRow.find('input.hidden_meta_default_value').val(meta_default_value);
		pTableRow.find('input.hidden_meta_list_values').val(meta_list_values);
	    } else {
		jQuery('tr#default-type-meta-row').instantiateAttribute(meta_name, meta_input_type, meta_default_value, meta_list_values);

	    }
	    jQuery('div#silk-cms-type-meta-editor').hide('fast', function(){  jQuery('div#silk-cms-type-meta-list').show('fast'); });
	},

	'openEditor': function(pTableRow){

	    jQuery('button#update-type-meta').entwine({

		'onclick': function(event){
		    jQuery('div#silk-cms-type-meta-editor').commitEditor(pTableRow);
		    return false;
		}
	    });

	    jQuery('button#cancel-type-meta').entwine({

		'onclick': function(event){
		    jQuery('div#silk-cms-type-meta-editor').hide('fast', function(){  jQuery('div#silk-cms-type-meta-list').show('fast'); });
		    return false;
		}
	    });

	    //Show appropriate fields depending on input type
	    jQuery('select#type-meta-input-type').entwine({
		'onchange': function(){
		    var type_val = jQuery(this).val();
		    if (type_val == 'Select')
			jQuery('div#silk-cms-type-meta-editor').showListValueEditor(pTableRow, jQuery(this).val());
		}
	    });

	    jQuery(this).prepopulateEditor(pTableRow);

	    if (jQuery('select#type-meta-input-type').val() == 'Select'){
		jQuery(this).showListValueEditor(pTableRow);
	    } else
		jQuery(this).hideListValueEditor();

	    jQuery('div#silk-cms-type-meta-list').hide('fast', function(){ jQuery('div#silk-cms-type-meta-editor').show('fast'); });

	}

    });

    //Open Type Meta Editor form and edit existing attribute
    jQuery('a.meta-edit-link').entwine({
	'onclick': function(){
// 	    var mel = jQuery(this);
// 	    var meta_id = mel.attr('id').replace(/meta-edit-/, '');

	    jQuery('div#silk-cms-type-meta-editor').openEditor(jQuery(this).parent().parent());

	}
    });

    //Open Type Meta Editor form and create new attribute
    jQuery('a.meta-add-link').entwine({
	'onclick': function(){
	    jQuery('div#silk-cms-type-meta-editor').openEditor();
	}
    });

    //Remove existing attribute row
    jQuery('a.meta-delete-link').entwine({
	'onclick': function(){
	    jQuery(this).parent().parent().remove();
	}
    });

    //add new user in permissions dialog
    jQuery('tr#silk-permissions-default-user').entwine({

	'instantiateRow': function(pUserId, pUsername){
	    var newRow = jQuery(this).clone();

	    newRow.removeAttr('id');
	    newRow.find('td span.silk-permissions-username').html(pUsername);
	    newRow.find('input.silk-permissions-hidden-user_id').attr('name', 'user_permissions[user][]').val(pUserId);
	    newRow.find('input.silk-permissions-privilege').attr('name', 'user_permissions[privilege][' + pUserId + '][]');

	    jQuery('table#silk-permissions-user-permissions tbody').append(newRow);

	    newRow.show('fast');
	}
    });

    jQuery('select#silk-permissions-add-user').entwine({

	'addUser': function(){
	    var user_id = jQuery(this).val();
	    var username_present = false;

	    jQuery('input.silk-permissions-hidden-user_id').each(function(){
		if (jQuery(this).val() == user_id)
		    username_present = true;
	    });

	    if (!username_present){
		var username = jQuery('select#silk-permissions-add-user option[value="' + user_id + '"]').text();
		if (user_id)
		    jQuery('tr#silk-permissions-default-user').instantiateRow(user_id, username);
		else
		    alert('No user selected');
	    } else
		alert('User is already present');
	    return false;
	}
    });

    jQuery('button#silk-permissions-add-user-button').click(function(){
	jQuery('select#silk-permissions-add-user').addUser();
	return false;
    });

    //html syntax highlighting
    jQuery('textarea.ide.html').entwine({
	'onmatch': function(){
	    CodeMirror.fromTextArea(jQuery(this).attr('id'), {
		path: "/assets/scripts/codemirror/js/",
		parserfile: ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js"],
		stylesheet: [ "/assets/scripts/codemirror/css/xmlcolors.css", "/assets/scripts/codemirror/css/csscolors.css", "/assets/scripts/codemirror/css/jscolors.css" ],
//       	    lineNumbers: true,
    //  	    textWrapping: false,
		autoMatchParens:true,
		iframeClass: 'code',
		height: '500px',
		continuousScanning: 500
    //  	    tabMode: 'spaces'
    //  	    indentUnit: 4
	    });
	}
    });


    //php syntax highlighing
    jQuery('textarea.ide.php').entwine({

	'onmatch': function(){
	    CodeMirror.fromTextArea(jQuery(this).attr('id'), {
		path: "/assets/scripts/codemirror/js/",
		parserfile: ["../contrib/php/js/tokenizephp.js","../contrib/php/js/parsephp.js"],
		stylesheet: [ "/assets/scripts/codemirror/contrib/php/css/phpcolors.css" ],
    //FIXME: Why does this cause codemirror to die!?
//       	    lineNumbers: true,
    //  	    textWrapping: false,
		autoMatchParens:true,
		iframeClass: 'code',
		height: '500px',
		continuousScanning: 500
    // 	    tabMode: 'spaces'
    //  	    indentUnit: 4
	    });
	}
    });

}